const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const nutritionGoalSchema = new Schema(
  {
    userId: {
      type: Schema.Types.ObjectId,
      ref: 'User',
      required: true,
      unique: true,
      index: true,
    },
    caloriesGoal: {
      type: Number,
      required: true,
      min: 0,
    },
    nutritionGoals: {
      protein: {
        type: Number,
        min: 0,
        default: 0,
      },
      fat: {
        type: Number,
        min: 0,
        default: 0,
      },
      carbohydrate: {
        type: Number,
        min: 0,
        default: 0,
      },
      fiber: {
        type: Number,
        min: 0,
        default: 0,
      },
      sugar: {
        type: Number,
        min: 0,
        default: 0,
      },
      sodium: {
        type: Number,
        min: 0,
        default: 0,
      },
    },
    macroRatio: {
      protein: {
        type: Number,
        min: 0,
        max: 100,
        default: 0,
      },
      fat: {
        type: Number,
        min: 0,
        max: 100,
        default: 0,
      },
      carbohydrate: {
        type: Number,
        min: 0,
        max: 100,
        default: 0,
      },
    },
    isDeleted: {
      type: Boolean,
      default: false,
      index: true,
    }
  },
  {
    timestamps: true,
    collection: 'nutrition_goals'
  }
);

// 添加验证：确保宏量营养素比例总和为100
nutritionGoalSchema.pre('save', function(next) {
  if (this.isModified('macroRatio')) {
    const { protein, fat, carbohydrate } = this.macroRatio;
    const sum = protein + fat + carbohydrate;
    if (sum !== 0 && Math.abs(sum - 100) > 0.01) {
      return next(new Error('宏量营养素比例总和必须为100%'));
    }
  }
  next();
});

/**
 * @typedef NutritionGoal
 */
const NutritionGoal = mongoose.model('NutritionGoal', nutritionGoalSchema);

module.exports = NutritionGoal; 